{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from itertools import count"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## algorithm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def spiral(n):\n",
    "    matrix = [range(i * n + n)[-n:] for i in range(n)]\n",
    "    X, C, R = {}, count(1), matrix\n",
    "\n",
    "    while R:\n",
    "        X.update(zip(R[0], C))\n",
    "        R = list(zip(*[i[::-1] for i in R[1:]]))\n",
    "\n",
    "    return [[X[j] for j in i] for i in matrix]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\t2\t3\n",
      "8\t9\t4\n",
      "7\t6\t5\n"
     ]
    }
   ],
   "source": [
    "for i in spiral(3):\n",
    "    print('\\t'.join(map(str, i)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\t2\t3\t4\t5\n",
      "16\t17\t18\t19\t6\n",
      "15\t24\t25\t20\t7\n",
      "14\t23\t22\t21\t8\n",
      "13\t12\t11\t10\t9\n"
     ]
    }
   ],
   "source": [
    "for i in spiral(5):\n",
    "    print('\\t'.join(map(str, i)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
